package com.example.javabasic.thread.classone.demo5;

import java.util.Optional;
import java.util.stream.Stream;

/**
 * 线程通信
 */
public class Test {
    public static void main(String[] args) {
        testLock();
    }


    public static void testLock() {
        final BooleanLock booleanLock = new BooleanLock();
        Stream.of("A","B","C","D","E","F","G","H","I","J").forEach(name->{
            //循环创建线程 去抢占锁
            new Thread(()->{
                try {
                    //持有锁 再执行任务
                    booleanLock.lock(100);
                    //执行任务
                    work();
                    Optional.of(Thread.currentThread().getName() +" 线程工作完成!");
                } catch (InterruptedException e) {
                    System.out.println("booleanLock.lock() 异常");
                } catch (Lock.TimeOutException e) {
                    System.out.println(e.getMessage());
                } finally{
                    //确保 任何情况下释放锁
                    //TODO  当 lock 锁  在工作完成后   要释放锁
                    booleanLock.unLock();
                    Optional.of(booleanLock).ifPresent(b ->{
                        System.out.println("被阻塞的线程个数:"+b.getBlockedSize());
                    });
                }
            },name).start();
        });
        Optional.of(booleanLock).ifPresent(b ->{
            System.out.println("被阻塞的线程个数:"+b.getBlockedSize());
        });
    }

    /**
     * 线程工作方法
     */
    public static void work() throws InterruptedException {
        Optional.of(Thread.currentThread().getName()+" 线程开始工作>>").ifPresent(System.out::println);
        //睡眠2秒
        Thread.sleep(5000);
    }
}
